package com.itrip.log.module.web;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itrip.log.module.db.IDao;
import com.itrip.log.module.task.EmailSummaryTask;
import com.itrip.log.util.Util;

/**
 * Function:XXX TODO add desc
 *
 * @date:2016年7月26日/下午6:07:27
 * @Author:jeff@aoliday.cao
 * @version:1.0
 */
@Controller
@RequestMapping("/ui")
public class EasyUIServer implements ApplicationListener<ContextRefreshedEvent> {

	@Autowired
	@Qualifier("daoTemplate")
	private IDao daoTemplate;

	@Autowired
	private EmailSummaryTask emailSummaryTask;

	private Logger log = LoggerFactory.getLogger(EasyUIServer.class);

	private HashMap<String, IDao> maps = new HashMap<String, IDao>();

	@ResponseBody
	@RequestMapping("/query")
	public JSONObject query(@RequestParam String params, int page, int rows, Integer total) throws Exception {
		JSONObject args = JSONObject.parseObject(params);
		Class<?> cls = Class.forName((String) args.remove("class"));
		String simpleName = cls.getSimpleName();
		IDao daoObj = getDaoObj(simpleName);

		if (total == null) {
			total = daoObj.count(simpleName, args);
		}

		args.put("start", (page - 1) * rows);
		args.put("size", rows);
		List<Object> datas = daoObj.getListByMap(simpleName, args);
		args.put("total", total);
		args.put("rows", datas);
		return args;
	}

	@ResponseBody
	@RequestMapping("/select")
	public Object select(@RequestParam String id, String params) throws Exception {
		JSONObject args = new JSONObject();
		if (params != null) {
			args = JSONObject.parseObject(params);
		}
		return daoTemplate.selectList(id, args);
	}

	@ResponseBody
	@RequestMapping("/report")
	public Object report(@RequestParam String id, @RequestParam String params, String countId, int page, int rows,
			Integer total) throws Exception {
		JSONObject args = JSONObject.parseObject(params);
		args.put("total", 10000);// 只点击上下页,total为最大值
		args.put("start", (page - 1) * rows);
		args.put("size", rows);
		args.put("rows", daoTemplate.selectList(id, args));
		return args;
	}

	@ResponseBody
	@RequestMapping("/save")
	public Object save(@RequestParam String params) throws Exception {
		JSONObject args = JSONObject.parseObject(params);
		String className = (String) args.remove("class");
		Class<?> cls = Class.forName(className);
		String namespace = cls.getSimpleName();
		Object obj = JSON.toJavaObject(args, cls);
		return getDaoObj(className).save(namespace, obj);
	}

	@ResponseBody
	@RequestMapping("/update")
	public boolean update(@RequestParam String params) throws Exception {
		JSONObject args = JSONObject.parseObject(params);
		String className = args.getString("class");
		Class<?> cls = Class.forName(className);
		String namespace = cls.getSimpleName();
		Object obj = JSON.toJavaObject(args, cls);
		return getDaoObj(className).update(namespace, obj) > 0;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public boolean delete(@RequestParam String params) throws ClassNotFoundException {
		JSONObject args = JSONObject.parseObject(params);
		String className = args.getString("class");
		Class<?> cls = Class.forName(className);
		String namespace = cls.getSimpleName();
		long id = args.getLongValue("id");
		return getDaoObj(className).delete(namespace, id) > 0;
	}

	private IDao getDaoObj(@RequestParam String namespace) {
		IDao dao = maps.get(namespace);
		return dao = dao == null ? daoTemplate : dao;
	}

	@ResponseBody
	@RequestMapping("/queryReport")
	public Object queryReport(String queryId, String param) throws ParseException {
		long startTime = System.currentTimeMillis();
		JSONObject json = JSONObject.parseObject(param);
		List<Object> data = daoTemplate.selectKeyValues(queryId, json);
		JSONObject result = new JSONObject();
		result.put("data", data);
		result.put("times", Util.timeCostSec(startTime));
		log.info("query condtion is {},times:{}", json, result.getFloat("times"));
		return result;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent arg0) {
		ApplicationContext ctx = arg0.getApplicationContext();
		Map<String, IDao> beans = ctx.getBeansOfType(IDao.class);
		for (Entry<String, IDao> item : beans.entrySet()) {
			IDao value = item.getValue();
			String processClassNames = value.processClassName();
			if (processClassNames == null) {
				log.info("DaoItf.processClassName is null:{}", value);
			} else {
				for (String cls : processClassNames.split(",")) {
					maps.put(cls, value);
				}
			}

		}
	}

}
